package com.github.ghsea.framework.job.support;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;

import com.github.ghsea.framework.job.common.TriggerMetadata;
import com.github.ghsea.framework.job.core.JobDataMapWrapper;
import com.github.ghsea.framework.job.core.StubJob;

public class TriggerMetadataUtil {

	private TriggerMetadata triggerMeta;

	public TriggerMetadataUtil(TriggerMetadata triggerMeta) {
		this.triggerMeta = triggerMeta;
	}

	public Trigger buildTrigger() {
		Trigger ret = null;

		if (triggerMeta.getCronExpression() != null) {
			String ctName = triggerMeta.getAppName() + "-cron-trigger";
			ret = TriggerBuilder.newTrigger().withIdentity(ctName, triggerMeta.getAppName())
					.withSchedule(CronScheduleBuilder.cronSchedule(triggerMeta.getCronExpression())).build();
		} else {

			// String stName = jobInfo.getAppName() + "-simple-trigger";
			Integer repeatCount = triggerMeta.getRepeatCount();
			Integer repeatIntervelInMs = triggerMeta.getRepeatIntervalInMs();
			Integer repeatIntervelInSec = repeatIntervelInMs < 1000 ? 1 : repeatIntervelInMs / 1000;
			// TriggerBuilder tb = TriggerBuilder.newTrigger().withIdentity(stName,
			// jobInfo.getAppName()).build();
			if (repeatCount != null) {
				ret = SimpleScheduleBuilder.repeatSecondlyForTotalCount(repeatCount, repeatIntervelInSec).build();
			} else {
				ret = SimpleScheduleBuilder.repeatSecondlyForever(repeatIntervelInSec).build();
			}
		}
		return ret;

	}

	public JobDetail buildJobDetail() {
		JobDataMapWrapper dataMap = new JobDataMapWrapper();
		dataMap.putJobClass(triggerMeta.getJobClass());

		JobDetail job = JobBuilder.newJob(StubJob.class)
				.withIdentity(triggerMeta.getJobName(), triggerMeta.getAppName()).usingJobData(dataMap).build();

		return job;
	}

}
